package com.example.test.service;

import com.example.test.entity.Image;
import com.example.test.mapper.ImageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Service
public class ImageService {

    // Directory where additional product images will be stored
    private static final String UPLOAD_DIR = "uploads/";
    private static final String ABSOLUTE_UPLOAD_DIR = "C:\\Users\\86183\\Desktop\\jiaoyi\\uploads";
    @Autowired
    private ImageMapper imageMapper;

    public void uploadImages(Long productId, List<MultipartFile> files) throws IOException {
        List<String> imagePaths = new ArrayList<>();

        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                String fileName = System.currentTimeMillis() + "-" + encodeFileName(file.getOriginalFilename());
                Path localFilePath = Paths.get(ABSOLUTE_UPLOAD_DIR + fileName);
                Files.copy(file.getInputStream(), localFilePath);
                imagePaths.add(UPLOAD_DIR + fileName); // Save relative path in database
            }
        }

        if (!imagePaths.isEmpty()) {
            imageMapper.insertProductImage(new Image(productId, imagePaths.get(0))); // Assuming productId is for the main image
        }
    }

    public List<String> getProductImages(Long productId) {
        return imageMapper.getProductImages(productId);
    }

    public void deleteProductImage(Long imageId) {
        String imagePath = imageMapper.getImageById(imageId);
        if (imagePath != null) {
            try {
                Files.deleteIfExists(Paths.get(ABSOLUTE_UPLOAD_DIR + getFileNameFromPath(imagePath)));
            } catch (IOException e) {
                e.printStackTrace();
            }
            imageMapper.deleteProductImage(imageId);
        }
    }

    public void deleteProductImagesByProductId(Long productId) {
        List<String> imagePaths = imageMapper.getProductImages(productId);
        for (String imagePath : imagePaths) {
            try {
                Files.deleteIfExists(Paths.get(ABSOLUTE_UPLOAD_DIR + getFileNameFromPath(imagePath)));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        imageMapper.deleteProductImagesByProductId(productId);
    }

    private String encodeFileName(String fileName) {
        return fileName.replaceAll("[^a-zA-Z0-9\\.\\-]", "_");
    }

    private String getFileNameFromPath(String path) {
        return Paths.get(path).getFileName().toString();
    }

    public List<Image> getProductImagesByProductId(Long productId) {
        return imageMapper.getProductImagesByProductId(productId);
    }
}
